package com.barryredmond.com;

//Sun's serial port driver
import gnu.io.*;

import java.io.*;
import java.util.*;

import org.apache.log4j.Logger;

/**
 * http://dn.codegear.com/article/31915
 * 
 * http://www.rxtx.org/
 *  *
 */
public class ComConnection {

	static Logger logger = Logger.getLogger(ComConnection.class);
	
	private CommPortIdentifier portId;
	private InputStream inputStream;
	private SerialPort serialPort;
	
	public ComConnection(String comPort) throws IOException, PortInUseException, NoSuchPortException, UnsupportedCommOperationException {

		try {
			portId = CommPortIdentifier.getPortIdentifier(comPort);
		} catch (NoSuchPortException e) {
			logger.error("COM4 " + portId);
			logger.error(e);
			throw e;
		}
		
		try {
			serialPort = (SerialPort) portId.open("ComControl", 2000);
			logger.info(portId.getName() + " opened for scanner input");
		} catch (PortInUseException e) {
			logger.error(e);
			throw e;
		}

		try {
			inputStream = serialPort.getInputStream();
		} catch (IOException e) {
			logger.error(e);
			throw e;
		}
		
		serialPort.notifyOnDataAvailable(true);
		
		try {
			serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
					SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

			serialPort.setDTR(false);
			serialPort.setRTS(false);

		} catch (UnsupportedCommOperationException e) {
			logger.error(e);
			throw e;
		}
	}
	
	public InputStream getInputStream(){
		return inputStream;
	}
	
	public void setSerialPortEventListener(SerialPortEventListener eventListener) throws TooManyListenersException{
		// Add an event listener
		serialPort.addEventListener(eventListener);
	}
	
}